const { default: classNames } = require('classnames')
const { formItemBehavior } = require('../behaviors')
const _ = require('../utils')

_.create('uploader', {
  properties: {
    title: {
      type: String,
      value: '',
    },
    desc: {
      type: String,
      value: '点击这里上传照片',
    },
    bordered: {
      type: Boolean,
      value: true,
    },
    maxSize: {
      type: Number,
      value: 2,
    },
    maxCount: {
      type: Number,
      value: 1,
    },
    sourceType: {
      type: Array,
      value: ['album', 'camera'],
    },
    sizeType: {
      type: Array,
      value: ['original', 'compressed'],
    },
  },
  data: {
    images: [],
  },
  behaviors: ['wx://form-field', formItemBehavior],
  computed: {
    classes(data) {
      const { classPrefix, bordered, error } = data
      const classes = classNames(classPrefix, {
        [`${classPrefix}-bordered`]: bordered,
        [`${classPrefix}-error`]: error,
      })
      return classes
    },

    tips(data) {
      const { maxCount, maxSize, images } = data
      let tips = ''
      if (maxCount > 1) {
        tips += `最多上传 ${maxCount}/${images.length} 个文件`
      }
      if (maxSize > 0) {
        if (tips) tips += ', '
        tips += `每个文件不能超过 ${maxSize} Mb` // 1048576
      }
      return tips
    },
  },
  relations: {
    '../form-validator/index': {
      type: 'ancestor',
    },
  },

  observers: {
    value: function (val) {
      this.setData({ images: Array.isArray(val) ? val : [val] })
    },
  },

  methods: {
    onTap() {
      const { maxSize, maxCount, sourceType, sizeType } = this.data
      const options = {
        sourceType,
        sizeType,
        count: maxCount,
        mediaType: ['image'],
      }
      const p = wx.canIUse('wx.chooseMedia') ? wx.chooseMedia(options) : wx.chooseImage(options)
      p.then((res) => {
        const { tempFiles, tempFilePaths } = res
        if (maxSize > 0) {
          const oversizeFiles = tempFiles.filter((f) => f.size > maxSize * 1048576)
          if (oversizeFiles.length > 0) {
            return this.triggerEvent('error', { files: oversizeFiles })
          }
        }

        return this.triggerEvent('select', { images: tempFilePaths })
      })
        // eslint-disable-next-line no-console
        .catch((e) => console.error(e))
    },

    removeImage(e) {
      const { index } = e.currentTarget.dataset
      this.triggerEvent('remove', { index })
    },
  },
})
